//导入request.js请求工具
import request from '@/utils/request.js'
import { encrypt } from '@/utils/aesUtil.js'
//提供调用注册接口的函数
export const userRegisterService = registerData => {
  //借助于UrlSearchParams完成传递
  const params = new URLSearchParams()
  for (let key in registerData) {
    params.append(key, registerData[key])
  }
  return request.post('/users', params)
}

export const userLoginService = loginData => {
  // 对密码进行加密
  loginData.password = encrypt(loginData.password)
  return request.post(`/users/login`, loginData)
}

//获取用户详细信息
export const userInfoService = username => {
  return request.get(`/users/userinfo/${username}`)
}

//修改个人信息
export const userInfoUpdateService = userInfoData => {
  return request.put('/users/userinfo', userInfoData)
}

//修改头像
export const userAvatarUpdateService = avatarUrl => {
  const params = new URLSearchParams()
  params.append('avatarUrl', avatarUrl)
  return request.patch('/users/avatar', params)
}

//修改密码
export const userUpdatePasswordService = ({
  old_pwd,
  new_pwd,
  re_pwd,
  token
}) =>
  request.patch(
    '/users/password',
    { old_pwd, new_pwd, re_pwd },
    { headers: { Authorization: token } }
  )

export const userAdd = user => {
  let username = user.username
  let password = user.password
  let email = user.email
  let nickname = user.nickname
  let roleId = user.roleId
  return request.post('/users/newuser', {
    username,
    password,
    email,
    nickname,
    roleId
  })
}

export const getUserList = userList => {
  let username = userList.username
  let currentPage = userList.currentPage
  let pageSize = userList.pageSize
  let total = userList.total

  // 将参数封装到一个对象中
  const params = {
    username: username,
    currentPage: currentPage,
    pageSize: pageSize,
    total: total
  }
  return request.get('/users', { params })
}

export const getRoles = userId => {
  return request.get(`/users/rolelist/${userId}`)
}

export const userDelete = userId => {
  return request.delete(`users/${userId}`)
}

export const editApi = user => {
  return request.put('/users', user)
}
//查询菜单树
export const getAssignTreeApi = parm => {
  return request.get(`/user/assignTree/${parm.userId}/${parm.roleId}`)
}

export const getEmailCode = email => {
  return request.get('/users/email', { params: { email: email } })
}

export const updatePswByEmail = data => {
  // 对新密码进行加密
  data.newPwd = encrypt(data.newPwd)
  // 对确认密码进行加密
  data.rePwd = encrypt(data.rePwd)
  console.log(data)
  return request.patch(`/users/forgetpassword`, data)
}

export const getUsernameByInput = email => {
  return request.get(`/users/username/${email}`)
}

export const permissionSearch = username => {
  return request.post('/auths', { username })
}
